import { ref, reactive } from 'vue'
import { toast, confirm, showFullLoading, hideFullLoading } from '@/utils/utils'
export default async function PugTableCommon(options = {}) {

    // 1： 搜索对象
    const searchForm = reactive({});

    if (options.searchForm) {
        searchForm = reactive({...options.searchForm })
        resetSearchForm = () => {
            for (const key in options.searchForm) {
                searchForm[key] = options.searchForm[key]
            }
            loadData()
        }
    }

    // 2：重置搜索
    const resetSearchForm = reactive({});

    // 3: 数据加载相关
    const tableData = ref([{
            id: 1,
            date: '2016-05-03',
            name: 'Tom',
            status: 1,
            address: 'No. 189, Grove St, Los Angeles',
        },
        {
            id: 2,
            date: '2016-05-02',
            name: 'Tom',
            status: 0,
            address: 'No. 189, Grove St, Los Angeles',
        },
        {
            id: 3,
            date: '2016-05-04',
            name: 'Tom',
            status: 1,
            address: 'No. 189, Grove St, Los Angeles',
        },
        {
            id: 4,
            date: '2016-05-01',
            name: 'Tom',
            status: 0,
            address: 'No. 189, Grove St, Los Angeles',
        },
    ]);


    const pageNo = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const pages = ref(0);

    // 4：数据加载
    const loading = ref(false);
    const loadData = async(pno = 1) => {
        if (typeof pno == "number") {
            pageNo.value = pno
        }

        try {
            loading.value = true;
            // 异步请求地址
            const res = await options.loadData(pageNo.value, searchForm);
            if (options.onSuccess && typeof options.onSuccess == "function") {
                options.onSuccess(res)
            } else {
                tableData.value = res.list
                total.value = res.totalCount
                pages.value = res.pages;
            }
        } finally {
            loading.value = false
        }
    };

    // 5: 数据初始化
    loadData();


    // 6：表格删除和编辑处理
    const handleEdit = (index, row) => {
        console.log(index, row)
    }
    const handleDelete = (index, row) => {
        console.log(index, row)
    }

    return {
        handleEdit,
        handleDelete,
        searchForm,
        resetSearchForm,
        tableData,
        pageNo,
        pageSize,
        total,
        pages,
        loadData
    }
}